package com.mmall.util;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.*;

public class SendMailFile {
    // MIME邮件对象
    private static MimeMessage mimeMsg;

    // 邮件会话对象
    private static Session session;
    // 系统属性
    private static Properties properties= System.getProperties();;
    // Multilpart对象，邮件内容，标题，附件等内容均添加到其中后再生成
    private static Multipart mp;
    // 发件人用户名
    private static String username="251231466@qq.com";
    // 发件人密码
    private static String password="whgodxpzprmccacb";
    // 发件人昵称
    private static String nickname="wanghao";

    // 收件人
    private static String sendName="ssrs_wanghao@163.com";
    // smtp
    private static String smtp="smtp.qq.com";

    public static void main(String[] args) {

        //设置邮件发送的SMTP主机
        properties.put("mail.smtp.host", smtp);
        properties.put("mail.smtp.auth", "true");

        if(smtp!=null && smtp.indexOf("qq")>0){
            // 下面四行不加也可以发送      QQ邮箱设置
            System.out.println("进入setQQ 加密");
            MailSSLSocketFactory sf = null;
            try {
                sf = new MailSSLSocketFactory();
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
            assert sf != null;
            sf.setTrustAllHosts(true);

            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
        }


        // 获取邮件会话对象
       session = Session.getDefaultInstance(properties,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication()
            {
                return new PasswordAuthentication(username, password); //发件人邮件用户名、密码
            }
        });


        // 创建邮件MIME对象
        mimeMsg = new MimeMessage(session);
        mp = new MimeMultipart();
        try {
            nickname = MimeUtility.encodeText(nickname, "utf-8", "B");
            mimeMsg.setFrom(new InternetAddress(nickname + "<" + username + ">"));
            // 将收件人数组设置为InternetAddress数组类型
            String [] receivers= new String[] {sendName};
            List<InternetAddress> receiverList = new ArrayList<InternetAddress>();
            for (String receiver : receivers) {
                receiverList.add(new InternetAddress(receiver));
            }
            InternetAddress[] addresses = receiverList.toArray(new InternetAddress[receivers.length]);
            mimeMsg.setRecipients(Message.RecipientType.TO, addresses);

            // 将抄送人数组设置为InternetAddress数组类型
            String [] copyTos = new String[0];
            List<InternetAddress> copyToList = new ArrayList<InternetAddress>();
            for (String copyto : copyTos) {
                copyToList.add(new InternetAddress(copyto));
            }
            InternetAddress[] copyAddresses = copyToList.toArray(new InternetAddress[copyTos.length]);
            mimeMsg.setRecipients(Message.RecipientType.CC, copyAddresses);

            Map<String,String> map = new HashMap<>();
            map.put("file1","C:/Users/Administrator/Desktop/teset.txt");
            map.put("file2","C:/Users/Administrator/Desktop/teset - 副本.txt");
            setFileAffix(map);

            mimeMsg.setSubject(MimeUtility.encodeText("主题：测试发送邮件带文件", "utf-8", "B"));
            // 内容
            BodyPart bp = new MimeBodyPart();
            bp.setContent("" + "<!DOCTYPE html>\n" +
                    "<html lang=\"en\">\n" +
                    "<head>\n" +
                    "    <meta charset=\"UTF-8\">\n" +
                    "    <title>Title</title>\n" +
                    "    <script type=\"text/javascript\">\n" +
                    "        function f() {\n" +
                    "            alert('你点击了');\n" +
                    "        }\n" +
                    "    </script>\n" +
                    "</head>\n" +
                    "<body>\n" +
                    "    <h1 style=\"color: red\" onclick=\"f()\">这是一封测试发送邮件带附件的邮件</h1>\n" +
                    "<p style=\"color: #000bff;\">不用回复，我就看下css样式</p>\n" +
                    "<input type=\"button\" onclick=\"f()\"  value=\"我是一个按钮\"/>\n" +
                    "</body>\n" +
                    "</html>\n", "text/html;charset=utf-8");
            mp.addBodyPart(bp);

            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();

            Transport transport = session.getTransport("smtp");
            transport.connect((String) properties.get("mail.smtp.host"), username, password);
            transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
            transport.close();



        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }


    }

    public static void setNamePass(String username, String password, String nickname) {
        username = username;
        password = password;
        nickname = nickname;
    }


    /**
     * 添加邮件附件，附件可为多个
     * @param fileMap 文件绝对路径map集合
     * @throws MessagingException
     */
    public static void setFileAffix(Map<String, String> fileMap) throws MessagingException, UnsupportedEncodingException {
        // 获取附件
        for (String file: fileMap.keySet()) {
            // 创建一个存放附件的BodyPart对象
            BodyPart bp = new MimeBodyPart();
            // 获取文件路径
            String filePath = fileMap.get(file);
            String[] fileNames = filePath.split("/");
            // 获取文件名
            String fileName = fileNames[fileNames.length-1];
            // 设置附件名称，附件名称为中文时先用utf-8编码
            bp.setFileName(MimeUtility.encodeWord(fileName, "utf-8", null));
            FileDataSource fields = new FileDataSource(filePath);
            bp.setDataHandler(new DataHandler(fields));
            // multipart中添加bodypart
            mp.addBodyPart(bp);
        }
    }

}
